<!--
	作者：939868405@qq.com
	时间：2018-10-05
	描述：差异调整审批
	应付员测试帐号：102631 111111
	订单号：8100028053 8100028554
-->
	
<!--<template>-->
<template>
	<div class="m-view-adjustBill m-window">
		<!--查询条件-->
		<div class="m-condition">
			<el-row :gutter="10">
				<el-col :span="3" :offset="13">
					<el-radio :disabled="radio_Disabled" v-model="radio" label="1" @change="changeRa">未审</el-radio>
					<el-radio :disabled="radio_Disabled" v-model="radio" label="2" @change="changeRa">已审</el-radio>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="search">查询</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="edit">浏览</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="appro" :disabled="btn_appro_Disabled">通过</el-button>
				</el-col>
				<el-col :span="2">
					<el-button type="primary" @click="return1" :disabled="btn_return1_Disabled">退回</el-button>
				</el-col>
			</el-row>
			<el-row :gutter="10">
				<el-form
					:model="headerRuleForm"
					label-width="70px"
					:inline-message="true"
					label-position="left"
				>
					<el-col :span="6">
						<el-form-item label="公司" class="rightItem">
							<el-select v-model="companyCode" placeholder="请选择公司" value-key="id" ref="content" filterable>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="订单号" class="rightItem">
							<el-input v-model="purOrdNo" placeholder="请输入订单号" clearable @keyup.enter.native="search"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="申请日期" class="rightItem">
							<el-date-picker
								v-model="applySDate"
								type="date"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								:editable="false"
								:picker-options="po1"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-date-picker
							v-model="applyEDate"
							type="date"
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
							:editable="false"
							:picker-options="po2"
						></el-date-picker>
					</el-col>
				</el-form>
			</el-row>
		</div>
		<!--差异调整列表-->
		<div class="m-agTable m-top2 m-bottom">
			<ag-grid-component
				ref="agGridComponent"
				:getColumnDefs="columnDefs"
				:getRowSelection="'multiple'"
				:tableName="'adjustAudit'"
				:getGridOptions="gridOptions"
				:getRowData="rowData"
				:isColFit="true"
                :systemInfo="$systemInfo"
				v-loading="loading"
			></ag-grid-component>
		</div>
		<div class="m-page">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="currentPage"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="total"
			></el-pagination>
		</div>
		<!--浏览差异调整-->
		<el-dialog
			:title="title"
			:visible.sync="dialogVisible"
			width="60%"
			v-dialogDrag
			:before-close="handleClose"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
			class="m-recordTable"
		>
			<el-form
				:model="ruleForm"
				ref="ruleForm"
				label-width="100px"
				class="demo-ruleForm"
				:rules="rules"
			>
				<!--第一行、订单号和行号-->
				<el-row>
					<el-col :span="12">
						<el-form-item label="订单号：" prop="purOrdNo">
							<el-input v-model="ruleForm.purOrdNo" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="行号：" prop="purOrdMxNo">
							<el-input v-model="ruleForm.purOrdMxNo" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第二行、物料编号和物料描述-->
				<el-row>
					<el-col :span="12">
						<el-form-item label="物料编号：">
							<el-input v-model="ruleForm.matCode" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="物料描述：">
							<el-input v-model="ruleForm.matName" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第三行、订单数量和单位-->
				<el-row>
					<el-col :span="12">
						<el-form-item label="订单数量：">
							<el-input v-model="ruleForm.orderAmount" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="单位：">
							<el-input v-model="ruleForm.unitCode" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!-- 第四行、订单数量和单位 -->
				<el-row>
					<el-col :span="12">
						<el-form-item label="价格数量：">
							<el-input v-model="ruleForm.priceAmount" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="价格单位：">
							<el-input v-model="ruleForm.priceUnit" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第五行、订单单价和订单金额-->
				<el-row>
					<el-col :span="12">
						<el-form-item label="订单单价：">
							<el-input v-model="ruleForm.unitPrice" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="订单金额：">
							<el-input v-model="ruleForm.unitmoney" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第六行、实际单价和实际金额-->
				<el-row>
					<el-col :span="12">
						<el-form-item label="实际单价：" prop="realPrice">
							<el-input v-model="ruleForm.realPrice" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="实际金额：">
							<el-input v-model="ruleForm.realMoney" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第七行、差异金额-->
				<el-row>
					<el-col :span="12">
						<el-form-item label="差异金额：">
							<el-input v-model="ruleForm.diffMoney" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第八、九行、备注-->
				<el-row>
					<el-col :span="24">
						<el-form-item label="备注：" prop="remark">
							<el-input v-model="ruleForm.remark" type="textarea" :rows="3" :disabled="true"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<!--第十行、添加附件-->
				<el-form-item label="附件:">
					<upLoadfile :files="fileList" :config="fileConfig" :showBtn="false"></upLoadfile>
				</el-form-item>
			</el-form>
			<!--底部、通过和退回按钮-->
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取消</el-button>
				<el-button type="primary" :disabled="btn_appro2_dis" @click="appro2">通过</el-button>
				<el-button type="primary" @click="return2">退回</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import Msg from "@/public/message.js";
import upLoadfile from "@/components/upLoadFile";
import authInfo from "@/public/authInfo";
import gridOptions from 'lesso-common/public/gridOptions';

export default {
	data () {
		return {
			purOrdNo: "",//采购订单号
			radio: '1',//未审
			applySDate: "",//时间
			applyEDate: "",//时间
			ruleForm: {},
			headerRuleForm: {},
			radio_Disabled: false,
			btn_appro_Disabled: false,
			btn_return1_Disabled: false,
			columnDefs: [],
			rowData: [],
			loading: false,

			//
			dialogVisible: false,
			title: "",
			rules: {},
			btn_appro2_dis: false,
			fileList: [],
			upload_dis: true,
			upload_url: this.$uploadUrl,
			currentPage: 1,
			pageSize: 30,
			total: 0,
			current: 1,
			po1: {
				disabledDate: this.disabledDate1
			},
			po2: {
				disabledDate: this.disabledDate2
			},
			//  上传组件相关配置  
			fileConfig: {
				limits: 1,
				accept: '.pdf,.doc,.docx,.xls,.xlsx,.txt',
				maxSize: 20971520,
				multiple: true
			},
			//   已选择公司编码
			companyCode: '',
			// 公司下拉列表
			comOptions: []
		}
	},
	beforeMount () {
		this.gridOptions = Object.assign({
			context: {
				componentParent: this
			},
			rowSelection: "multiple",
			enableColResize: true,
			localeText: localeText,
			suppressRowClickSelection: true
		},gridOptions({dragSelectCheckbox:true,singleSelection: true,operation:true}))
		this.columnDefs = [

			{ headerName: "订单号", field: "purOrdNo", width: 140, checkboxSelection: true, headerCheckboxSelection: true, headerCheckboxSelectionFilteredOnly: true },
			{ headerName: "行号", field: "purOrdMxNo", width: 70 },
			{ headerName: "公司", field: "companyName", width: 200 },
			{ headerName: "供应商", field: "supplierName", width: 200 },
			{ headerName: "物料描述", field: "matName", width: 250, tooltipField: "matName" },
			{ headerName: "数量", field: "orderAmount", width: 100 },
			{ headerName: "订单单价", field: "unitPrice", width: 100 },
			{ headerName: "实际单价", field: "realPrice", width: 100 },
			{ headerName: "差异金额", field: "diffMoney", width: 100 },
			{ headerName: "备注", field: "remark", width: 150, tooltipField: 'remark' },
			{ headerName: "附件名称", field: "attachmentName", width: 150, tooltipField: 'attachmentName' },
			{ headerName: "创建人", field: "creator", width: 100, tooltipField: 'creator' },
			{ headerName: "创建日期", field: "createDate", width: 150 },
			{ headerName: "提交人", field: "submitter", width: 100, tooltipField: 'submitter' },
			{ headerName: "提交日期", field: "submitDate", width: 150 },
			{ headerName: "审核人", field: "auditor", width: 100 },
			{ headerName: "审核日期", field: "auditDate", width: 150 },
			{				headerName: "单据状态", field: "state", width: 100, cellRenderer: function (params) {
					if (params.value == "1")
						return '<span class="ag-icon">未审</span>';
					else if (params.value == "2")
						return '<span class="ag-icon">已审</span>';
				}			},
			{ headerName: "显示标识", field: "delFlag", hide: true },
			{ headerName: "id", field: "id", hide: true },
			{ headerName: "物料号", field: "matCode", hide: true },
			{ headerName: "单位", field: "unitCode", hide: true },
			{ headerName: "订单金额", field: "unitmoney", hide: true },
			{ headerName: "实际金额", field: "realMoney", hide: true },
			{ headerName: "附件地址", field: "url", hide: true },
			{ headerName: "审核人ID", field: "auditorId", hide: true },
		];
	},
	mounted () {
		this.getCompanyOption()
	},
	components: {
		upLoadfile
	},
	methods: {
		disabledDate1 (time) {
			if (this.applyEDate)
				return time.getTime() > new Date(this.applyEDate).getTime();
		},
		disabledDate2 (time) {
			if (this.applySDate)
				return time.getTime() < (new Date(this.applySDate).getTime() - 3600 * 1000 * 24);
		},
		handleSizeChange (params) {
			this.current = 1;
			this.currentPage = 1;
			this.pageSize = params;
			this.search();
		},
		handleCurrentChange (params) {
			this.current = params;
			this.currentPage = params;
			this.search();
		},
		handlePrevClick (params) {
			this.current = params;
			this.currentPage = params;
			this.search();
		},
		handleNextClick (params) {
			this.current = params;
			this.currentPage = params;
			this.search();
		},
		search () {
			var obj = {
				eqParams: {},
				likeParams: {},
				geParams: {},
				leParams: {}
			};

			if (this.purOrdNo.replace(/\s+/g, "") == "")
				;
			else
				obj.likeParams.purOrdNo = this.purOrdNo.replace(/\s+/g, "");//去掉文本框里的空格	

			obj.eqParams.delFlag = 0;//显示启用
			obj.eqParams.state = this.radio;//"1"//未审

			// if (this.applyDate[0] == null)
			// 	;
			// else
			// 	obj.geParams.begin_date=this.applyDate[0];

			// if (this.applyDate[1] == null)
			// 	;	
			// else
			// 	obj.leParams.end_date=this.applyDate[1];
			//jjc20181014
			if (this.companyCode) {
				obj.eqParams.companyCode = this.companyCode
			} else {
				Msg.showPopMsg('请先选择公司')
				return
			}
			if (this.applySDate != "" && this.applySDate != null) {
				obj.geParams.begin_date = this.applySDate;
				if (this.applyEDate == "" || this.applyEDate == null)
					obj.leParams.end_date = obj.geParams.begin_date;
			}
			if (this.applyEDate != "" && this.applyEDate != null) {
				obj.leParams.end_date = this.applyEDate;
				if (this.applySDate == "" || this.applySDate == null)
					obj.geParams.begin_date = obj.leParams.end_date;
			}
			if (obj.geParams.begin_date != "" && obj.leParams.end_date != "") {
				if (obj.geParams.begin_date > obj.leParams.end_date) {
					Msg.showPopMsg("提示：开始日期不能大于结束日期")
					return;
				}
			}
			obj.current = this.current;
			obj.size = this.pageSize;
			var that = this;
			this.loading = true;
            this.$refs["agGridComponent"].gridOptions.api.setColumnDefs(this.columnDefs)
			_Api.getAdjustbill(obj).then(function (response) {
				var data = response.data;
				that.loading = false;
				if (data.code == "1") {
					if (data.total > 0) {
						that.$refs["agGridComponent"].gridOptions.api.setRowData(data.rows);
						that.total = data.total;
					} else {
						that.$refs["agGridComponent"].gridOptions.api.setRowData([]);
						that.current = 1;
						that.total = 0;
					}
				}
				else {
					Msg.showErrorMsg(data.info);
					that.total = 0;
					that.current = 1;
				}
			}).catch((err) => {
				Msg.showErrorMsg(err.data.message);
				that.loading = false;
			})
		},
		changeRa (radio) {
			if (radio == '1')//未审
			{
				this.btn_appro_Disabled = false;//可编辑通过按钮
				this.btn_return1_Disabled = false;//可编辑退回按钮
				this.current = 1;
				this.search();
			}
			else//已审
			{
				this.btn_appro_Disabled = true;//停用通过按钮
				this.btn_return1_Disabled = false;//可编辑退回按钮
				this.current = 1;
				this.search();
			}
		},
		edit () {
			var row = this.$refs["agGridComponent"].gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				Msg.showPopMsg("提示：请选择一条想浏览的差异调整！")
				return;
			}
			else if (row.length > 1) {
				Msg.showPopMsg("提示：每次只能选择一条想浏览的差异调整！")
				return;
			}
			else {
				this.ruleForm = row[0];
				this.title = "浏览";
				this.dialogVisible = true;
				if (this.ruleForm.attachmentName == '')
					this.fileList = [];
				else
					this.fileList = [{ name: this.ruleForm.attachmentName, url: this.ruleForm.url }];
				if (this.radio == '1') {
					this.btn_appro2_dis = false;
				}
				else {
					this.btn_appro2_dis = true;
				}
			}
		},
		appro () {
			var row = this.$refs["agGridComponent"].gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				this.$alert("提示：请选择数据进行审批", {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"				});
				Msg.showPopMsg("提示：请选择数据进行审批")
				return;
			}
			else {
				var that = this;
				this.$confirm("是否通过数据？", "消息提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					distinguishCancelAndClose: true
				})
					.then(() => {
						var id = '';
						for (var i = 0; i < row.length; i++) {
							id += row[i].id + ',';
						}

						id = id.substr(0, id.length - 1);

						var obj = {
							id: id,
							auditState: 2,//审核标志
							auditorId: this.$global.user.id,//审核人ID
							auditor: this.$global.user.employeeName//审核人

						}
						_Api.review(obj).then(function (response) {
							var data = response.data;
							if (data.code == "1") {

								Msg.showSuccessMsg("已通过")
							}
							else {

								Msg.showErrorMsg(data.info);
							}
							that.search();
						})
							.catch((err) => {
								Msg.showErrorMsg(err.data.message);
							})
					})
					.catch(() => {

					})
			}
		},
		return1 () {
			var row = this.$refs["agGridComponent"].gridOptions.api.getSelectedRows();
			if (row.length <= 0) {
				Msg.showPopMsg("提示：请选择数据进行审批")
				return;
			}
			else {
				var that = this;
				this.$confirm("是否退回数据？", "消息提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					distinguishCancelAndClose: true
				})
					.then(() => {
						var id = '';
						for (var i = 0; i < row.length; i++) {
							id += row[i].id + ',';
						}

						id = id.substr(0, id.length - 1);

						var obj = {
							id: id,
							auditState: 0,//审核标志
							auditorId: this.$global.user.id,//审核人ID
							auditor: this.$global.user.employeeName//审核人

						}
						_Api.review(obj).then(function (response) {
							var data = response.data;
							if (data.code == "1") {
								Msg.showSuccessMsg("已退回")
							}
							else {
								Msg.showErrorMsg(data.info);
							}
							that.search();
						})
							.catch(() => {
								Msg.showErrorMsg("请求失败！");
							})
					})
					.catch(() => {

					})
			}
		},
		cancel () {
			var that = this;
			this.$refs.ruleForm.resetFields();
			this.$nextTick(_ => {
				that.$refs.ruleForm.clearValidate();
			});
			this.dialogVisible = false;
		},
		appro2 () {
			var that = this;
			var obj = {};
			obj.auditor = this.$global.user.employeeName//审核人
			obj.auditorId = this.$global.user.id//审核人ID
			obj.id = this.ruleForm.id//主键
			obj.auditState = 2;//单据状态为通过

			_Api.review(obj).then(function (response) {
				var data = response.data;
				if (data.code == "1") {

					Msg.showSuccessMsg("已通过")
					that.dialogVisible = false;
					that.search();
				}
				else {

					Msg.showErrorMsg(data.info);
				}
			})
				.catch(() => {
					Msg.showErrorMsg("请求失败！");
				});
		},
		return2 () {
			var that = this;
			var obj = {};
			obj.auditor = this.$global.user.employeeName//审核人
			obj.auditorId = this.$global.user.id//审核人ID
			obj.id = this.ruleForm.id//主键
			obj.auditState = 0;//单据状态为保存

			_Api.review(obj).then(function (response) {
				var data = response.data;
				if (data.code == "1") {
					Msg.showSuccessMsg("已退回")
					that.dialogVisible = false;
					that.search();
				}
				else {
					Msg.showErrorMsg(data.info);
				}
			})
				.catch(() => {
					Msg.showErrorMsg("请求失败！");
				});
		},
		handleClose (done) {
			this.$refs.ruleForm.resetFields();
			this.$refs.ruleForm.clearValidate();
			done();
		},
		downLoadFile (item) {
			console.log('返回的文件url为blob形式', item)
			// var group = ''
			// if (item.url.indexOf('SRM') > -1) {
			//     group = 'SRM'
			// } else if (item.url.indexOf('SIGN') > -1) {
			//     group = 'SIGN'
			// } else if (item.url.indexOf('TEST') > -1) {
			//     group = 'TEST'
			// } else if (item.url.indexOf('MES') > -1) {
			//     group = 'MES'
			// }
			// var obj = {
			//     viewPath: item.url,
			//     groupName: group,
			//     fileName:''
			// };
			// downLoadFileFunc(obj,item.name)
			this.downLoad(item.name, item.url)
			// 	            var obj = {
			// 	                url:item.url
			// 	            };
			// 	            var that = this;
			// 	            _Api.downLoadFile(obj).then(function(response){
			// 	                var data = response.data;
			// 	                if(data.code == "1")
			// 	                {
			// 	                    if(data.total > 0)
			// 	                    {
			// //	                        console.log(data.rows[0].fileName);
			// 	                        that.downLoad(item.name,data.rows[0].fileName);//data.rows[0].filename
			// 	                    }
			// 	                }
			// 	            })
		},
		downLoad (filename, url) {
			var eleLink = document.createElement('a');
			eleLink.style.display = 'none';
			eleLink.setAttribute("href", url);   //文件下载地址
			//	            eleLink.setAttribute("href.name",filename);
			eleLink.setAttribute("download", filename);  //download属性只能在同域实现
			// 触发点击
			document.body.appendChild(eleLink);
			eleLink.click();
			// 然后移除
			document.body.removeChild(eleLink);
		},
		handlePreview (file) {
			//      		console.log(file.url);
			this.downLoadFile(file);
		},
		// 根据账户类型获取公司下拉列表
		getCompanyOption () {
			authInfo.getAuthInfo().then(data => {
				this.comOptions = data
				this.companyCode = this.comOptions[0].companyCode
				this.search()
			})
				.catch(err => {
					this.$alert(err, {
						showClose: false,
						confirmButton: "确定",
						customClass: "alertFailure"
					});
				});
		}
	},
	watch: {
		purOrdNo (val) {
			if (val)
				this.current = 1;
			else
				this.current = this.currentPage;
		},
		applySDate (value) {
			if (value == null)
				this.applySDate = "";
			this.current = 1;
		},
		applyEDate (value) {
			if (value == null)
				this.applyEDate = "";
			this.current = 1;
		}
	}
}
</script>
